import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/bind', '/register']

router.beforeEach((to, from, next) => {
  console.log(to)
  NProgress.start()
  if (getToken()) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch('GetInfo')
          .then(res => {
            // 拉取user_info
            const roles = res.roles
            store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              console.log(store.state.permission.fullPathRoutes)
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              let homePath = ''
              let firstPath = ''
              // 未设置取第一个页面为首页
              if (
                store.state.permission.fullPathRoutes[0] &&
                store.state.permission.fullPathRoutes[0].children &&
                store.state.permission.fullPathRoutes[0].children.length
              ) {
                firstPath =
                  store.state.permission.fullPathRoutes[0].children[0].path
              } else {
                firstPath = store.state.permission.fullPathRoutes[0].path
              }
              // 找设置了affix的首页
              store.state.permission.fullPathRoutes.map(route => {
                if (route.children && route.children.length) {
                  route.children.map(c => {
                    if (c.meta && c.meta.affix) {
                      homePath = c.path
                    }
                  })
                } else {
                  if (route.meta && route.meta.affix) {
                    homePath = route.path
                  }
                }
              })
              // 有affix去affix，没affix去权限路由第一个
              if (
                (homePath && from.path === '/login') ||
                to.path === '/noredirect' ||
                to.path === '/Login'
              ) {
                console.log('进入设置了affix的首页：', homePath)
                next({
                  path: homePath,
                  replace: true
                })
              } else if (
                (!homePath && from.path === '/login') ||
                to.path === '/noredirect' ||
                to.path === '/Login'
              ) {
                console.log('未设置首页,进入第一个页面：', firstPath)
                next({
                  path: firstPath,
                  replace: true
                })
              } else {
                console.log('刷新界面进入：', to.path)
                next({
                  ...to,
                  replace: true
                })
              }
            })
          })
          .catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      // next(`/login?redirect='/index'`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
